import {PlusOutlined} from '@ant-design/icons'
import {
    Row,
    Col,
    Flex,
    Typography,
    Button,
    Form,
    Input,
    Select,
    Table,
    Switch,
    Drawer,
    Modal,
    Divider,
    Radio,
    message
} from 'antd'
import React, {useState} from 'react'
import {useEffect} from 'react'
import {
    msgFieldAPI,
    triggerMsgListAPI,
    triggerMsgEditAPI,
    triggerMsgDelAPI,
    triggerMsgAddAPI
} from '../service/message'

export default function TouchTriggerMsg() {
    const [title, setTitle] = useState('')
    const [content, setContent] = useState('')
    const [form] = Form.useForm()
    // 模态框
    const [modalOpen, setModalOpen] = useState(false)
    // 是否有选中活动
    const [selectedActive, setSelectedActive] = useState('选择插入字段')
    const [modalOpen2, setModalOpen2] = useState(false)
    const [selectedContent, setSelectedContent] = useState('')
    const [selectedTitle, setSelectedTitle] = useState('')
    const [isOpen, setIsOpen] = useState(false)
    const [page, setPage] = useState(1)
    const [triggerList, setTriggerList] = useState([])
    // 动态字段列表
    const [dynamicList, setDynamicList] = useState([])
    const [n, setN] = useState(0)
    const [id, setId] = useState('')
    const request = async () => {
        const res = await triggerMsgListAPI({pageNo: page, pageSize: 10})
        console.log(res)
        setTriggerList(res.data)
    }
    useEffect(() => {
        request()
        // 查询动态字段
        ;(async () => {
            const res = await msgFieldAPI()
            console.log(res)
            setDynamicList(res.data)
        })()
    }, [n])

    return (
        <>
            <Row className="info">
                <Col span={24}>
                    <Flex justify={'space-between'}>
                        <Typography.Title level={3}>信息管理</Typography.Title>
                        <Button
                            type="primary"
                            icon={<PlusOutlined/>}
                            onClick={() => {
                                setIsOpen(true)
                                setId('')
                            }}
                        >
                            新建触发消息
                        </Button>
                    </Flex>
                </Col>
            </Row>
            <Row className="container">
                <Col span={24}>
                    <Form layout="inline">
                        <Form.Item label="模板名称" name="storeName">
                            <Input style={{width: 200}}/>
                        </Form.Item>
                        <Form.Item label="模板状态" initialValue={'0'}>
                            <Select
                                style={{width: 200}}
                                placeholder="请选择模板状态"
                                options={[
                                    {
                                        value: '',
                                        label: '全部'
                                    },
                                    {
                                        value: '0',
                                        label: '启用'
                                    },
                                    {
                                        value: '1',
                                        label: '停用'
                                    }
                                ]}
                            />
                        </Form.Item>
                        <Form.Item>
                            <Button type="default" htmlType="reset">
                                重置
                            </Button>
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>
                        </Form.Item>
                    </Form>
                </Col>
            </Row>
            <Row className="container">
                <Col span={24}>
                    <Typography.Paragraph style={{fontSize: 16}}>
                        触发列表
                    </Typography.Paragraph>
                </Col>
                <Col span={24}>
                    <Table
                        rowKey="id"
                        dataSource={triggerList}
                        pagination={{pageSize: 10, onChange: (page) => setPage(page)}}
                        columns={[
                            {
                                title: '序号',
                                dataIndex: 'id',
                                key: 'id'
                            },
                            {
                                title: '模板名称',
                                dataIndex: 'tempName',
                                key: 'tempName'
                            },
                            {
                                title: '消息标题',
                                dataIndex: 'msgTitle',
                                key: 'msgTitle'
                            },
                            {
                                title: '用户行为',
                                dataIndex: 'userAction',
                                key: 'userAction'
                            },
                            {
                                title: '创建时间',
                                dataIndex: 'createAt',
                                key: 'createAt'
                            },
                            {
                                title: '启用状态',
                                dataIndex: 'status',
                                key: 'status',
                                render: (_, record) => (
                                    <Switch
                                        defaultChecked={record.status === 1}
                                        onChange={async (checked) => {
                                            const res = await triggerMsgEditAPI({
                                                id: record.id,
                                                status: record.status === 1 ? 0 : 1
                                            })
                                            setN(n + 1)
                                        }}
                                    />
                                )
                            },
                            {
                                title: '操作',
                                key: 'action',
                                render: (_, record) => (
                                    <span className="op">
                    <a
                        onClick={() => {
                            setIsOpen(true)
                            form.setFieldsValue(record)
                            setId(record.id)
                            // setActiveId(record.activityId)
                            setSelectedActive(record.msgTitle)
                        }}
                        style={{marginRight: 10}}
                    >
                      编辑
                    </a>
                    <a
                        onClick={async () => {
                            const res = await triggerMsgDelAPI(record.id)
                            console.log(res)
                            setN(n + 1)
                            message.success('删除成功')
                        }}
                    >
                      删除
                    </a>
                  </span>
                                )
                            }
                        ]}
                    />
                </Col>
            </Row>
            {/* 右侧抽屉 */}
            <Drawer
                title="新建触发消息"
                onClose={() => {
                    setIsOpen(false)
                }}
                open={isOpen}
                width={500}
                maskClosable={false}
                destroyOnClose
            >
                <Form
                    layout="vertical"
                    form={form}
                    preserve={false}
                    onFinish={async (values) => {
                        console.log(values)
                        if (id) {
                            // 编辑
                            const res = await triggerMsgEditAPI({...values, id})
                            console.log(res)
                            message.success('编辑成功')
                        } else {
                            // 添加
                            const res = await triggerMsgAddAPI(values)
                            console.log(res)
                            message.success('添加成功')
                        }
                        setIsOpen(false)
                        setId('')
                        setN(n + 1)
                    }}
                >
                    <Form.Item
                        label="模板名称"
                        name="tempName"
                        rules={[{required: true, message: '请输入模板名称'}]}
                    >
                        <Input/>
                    </Form.Item>
                    <Form.Item
                        label="用户行为"
                        name="userAction"
                        rules={[{required: true, message: '请选择用户行为'}]}
                    >
                        <Select
                            placeholder="请选择用户行为"
                            options={[
                                {
                                    value: '点赞',
                                    label: '点赞'
                                },
                                {
                                    value: '评论',
                                    label: '评论'
                                },
                                {
                                    value: '关注',
                                    label: '关注'
                                },
                                {
                                    value: '转发',
                                    label: '转发'
                                },
                                {
                                    value: '收藏',
                                    label: '收藏'
                                },
                                {
                                    value: '优惠券使用',
                                    label: '优惠券使用'
                                },
                                {
                                    value: '浏览',
                                    label: '浏览'
                                },
                                {
                                    value: '搜索',
                                    label: '搜索'
                                },
                                {
                                    value: '注册',
                                    label: '注册'
                                },
                                {
                                    value: '登录',
                                    label: '登录'
                                }
                            ]}
                        />
                    </Form.Item>
                    <Form.Item label="消息标题">
                        {/* <Select
              onClick={() => setModalOpen(true)}
              placeholder="请选择消息标题"
              value={selectedActive}
            /> */}
                        <Row>
                            <Col span={24}>
                                <Form.Item name="msgTitle">
                                    <Input
                                        onChange={(e) => {
                                            console.log(e.target.value)
                                            setTitle(e.target.value)
                                        }}
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={24} style={{marginTop: -22}}>
                <span
                    style={{
                        color: '#3961F3',
                        cursor: 'pointer'
                    }}
                    onClick={() => setModalOpen(true)}
                >
                  插入动态字段
                </span>
                            </Col>
                        </Row>
                    </Form.Item>
                    {/* <Form.Item>
            <span className="op">
              <a onClick={() => setModalOpen(true)}>选择插入字段</a>
            </span>
          </Form.Item> */}

                    <Form.Item label="消息内容">
                        <Row>
                            <Col span={24}>
                                <Form.Item name={'content'}>
                                    <Input.TextArea
                                        value={content}
                                        onChange={(e) => setContent(e.target.value)}
                                        maxLength={500}
                                        style={{height: 100}}
                                        showCount
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={24} style={{marginTop: -22}}>
                <span
                    style={{
                        color: '#3961F3',
                        cursor: 'pointer'
                    }}
                    onClick={() => setModalOpen2(true)}
                >
                  插入动态字段
                </span>
                            </Col>
                        </Row>
                    </Form.Item>

                    <Form.Item label="启用状态" name="status" initialValue={1}>
                        <Radio.Group>
                            <Radio value={1}>启用</Radio>
                            <Radio value={0}>禁用</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item style={{textAlign: 'right'}}>
                        <Button type="default" htmlType="reset" style={{marginRight: 10}}>
                            重置
                        </Button>
                        <Button type="primary" htmlType="submit">
                            确定
                        </Button>
                    </Form.Item>
                </Form>
            </Drawer>
            {/* 选择营销活动 */}
            <Modal
                title="字段列表"
                open={modalOpen}
                width={500}
                onCancel={() => setModalOpen(false)}
                onOk={() => {
                    let str = ''
                    // 循环获取每一项，并添加{}
                    selectedTitle.forEach((item) => {
                        // 拼接
                        str += '{' + item + '}'
                    })
                    form.setFieldsValue({
                        msgTitle: str
                    })
                    setModalOpen(false)
                }}
                destroyOnClose
                maskClosable={false}
            >
                <Divider/>
                <Row>
                    <Col span={24}>
                        <Form onFinish={() => {
                        }}>
                            <Input.Search placeholder="请输入字段名称"/>
                        </Form>
                    </Col>
                </Row>
                <Row style={{marginTop: 20}}>
                    <Col span={24}>
                        <Table
                            rowKey="id"
                            dataSource={dynamicList}
                            pagination={false}
                            rowSelection={{
                                type: 'checkbox',
                                onChange: (selectedRowKeys, selectedRows) => {
                                    console.log(selectedRowKeys, selectedRows)
                                    const selectedRowsName = selectedRows.map(
                                        (item) => item.fieldName
                                    )
                                    setSelectedTitle(selectedRowsName)
                                }
                            }}
                            columns={[
                                {key: 'id', title: '序号', dataIndex: 'id'},
                                {key: 'fieldValue', title: '字段名称', dataIndex: 'fieldValue'},
                                {key: 'fieldName', title: '字段', dataIndex: 'fieldName'}
                            ]}
                        />
                    </Col>
                </Row>
            </Modal>
            {/* 选择营销内容 */}
            <Modal
                title="字段列表"
                open={modalOpen2}
                width={500}
                onCancel={() => setModalOpen2(false)}
                onOk={() => {
                    let str = ''
                    // 循环获取每一项，并添加{}
                    selectedContent.forEach((item) => {
                        // 拼接
                        str += '{' + item + '}'
                    })
                    form.setFieldsValue({
                        content: str
                    })
                    setModalOpen2(false)
                }}
                destroyOnClose
                maskClosable={false}
            >
                <Divider/>
                <Row>
                    <Col span={24}>
                        <Form onFinish={() => {
                        }}>
                            <Input.Search placeholder="请输入字段名称"/>
                        </Form>
                    </Col>
                </Row>
                <Row style={{marginTop: 20}}>
                    <Col span={24}>
                        <Table
                            rowKey="id"
                            dataSource={dynamicList}
                            pagination={false}
                            rowSelection={{
                                type: 'checkbox',
                                onChange: (selectedRowKeys, selectedRows) => {
                                    console.log(selectedRowKeys, selectedRows)
                                    const selectedRowsName = selectedRows.map(
                                        (item) => item.fieldName
                                    )
                                    setSelectedContent(selectedRowsName)
                                    // form.setFieldsValue({
                                    //   content: '{' + selectedRows[0].fieldName + '}'
                                    // })
                                    // setModalOpen2(false)
                                }
                            }}
                            columns={[
                                {key: 'id', title: '序号', dataIndex: 'id'},
                                {key: 'fieldValue', title: '字段名称', dataIndex: 'fieldValue'},
                                {key: 'fieldName', title: '字段', dataIndex: 'fieldName'}
                            ]}
                        />
                    </Col>
                </Row>
            </Modal>
        </>
    )
}
